﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;
using System.Net.Configuration;
//using Aspose.Excel;

namespace LenderClearingHouse
{
  public class Utilities
  {
   /*private static HttpContext contextCurrent
    {
      get
      {
        return System.Web.HttpContext.Current;
      }
    }*/

    public static SqlConnection GetConnection()
    {
      SqlConnection myConnection;
      return myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString);
    }

    //Exports datasets to a csv file
   /* public static void ExportToSpreadsheet(DataTable table, string name)
    {
      HttpContext context = HttpContext.Current;
      context.Response.Clear();
      foreach (DataColumn column in table.Columns)
      {
        context.Response.Write(column.ColumnName + ",");
      }
      context.Response.Write(Environment.NewLine);
      foreach (DataRow row in table.Rows)
      {
        for (int i = 0; i < table.Columns.Count; i++)
        {
          context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
        }
        context.Response.Write(Environment.NewLine);
      }
      context.Response.ContentType = "text/csv";
      context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
      context.Response.End();
    }*/

    //Generate random password using Guid
    public static string GetRandomPassword(int length)
    {
      // Get the GUID
      string guidResult = System.Guid.NewGuid().ToString();

      // Remove the hyphens
      guidResult = guidResult.Replace("-", string.Empty);

      // Make sure length is valid
      if (length <= 0 || length > guidResult.Length)
        throw new ArgumentException("Length must be between 1 and " + guidResult.Length);

      // Return the first length bytes
      return guidResult.Substring(0, length);
    }


    //test for database connection
    public static bool TestConnection()
    {
      bool connected = false;
      SqlConnection myConnection = GetConnection();

      try
      {
        myConnection.Open();
        connected = true;
      }
      catch (Exception ex)
      {
        //Utilities.LogError(ex);
        throw ex;
      }
      finally
      {
        myConnection.Close();
      }
      return connected;
    }
	  /*
    //Generic method for sending emails
    public static void SendMail(string from, string to, string subject, string body)
    {
      //Configure mail client
      SmtpClient mailClient = new SmtpClient(ApplicationConfiguration.MailServer);
      //Create the mail message
      MailMessage mailMessage = new MailMessage(from, to, subject, body);

      //Send mail
      mailClient.Send(mailMessage);
    }//End SendMail

    public static void SendMail(string to, string subject, string text, string textHtml, out string error)
    {
      error = "";
      try
      {
        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;

        System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
        SmtpSection smtpSection = (SmtpSection)config.GetSection("system.net/mailSettings/smtp");

        MailMessage msg = new MailMessage();
        msg.From = new MailAddress(smtpSection.Network.UserName);

        msg.To.Add(to);
        msg.Subject = subject;
        msg.IsBodyHtml = (textHtml != "");
        msg.Body = (textHtml == "" ? text : textHtml);

        client.Send(msg);

      }
      catch (Exception ex)
      {
        error = ex.Message;
      }
    }

    public static Excel GetExcel()
    {
      License license = new License();
      license.SetLicense(contextCurrent.Server.MapPath("~/Aspose.Excel.lic"));
      Excel ex = new Excel();

      return ex;
    }

    /// <summary>
    /// Out data to Excel according to field list (by the template)
    /// </summary>
    /// <param name="data">Data array</param>
    /// <param name="listFields">List of fields</param>
    /// <param name="templateName">Template file name</param>
    /// <param name="showResult">Flag: true - show report, false - no</param>
    /// <param name="startRow">First row number</param>
    public static Excel GridToExcel(DataTable data, string[] listFields, string templateName, bool showResult, ref int startRow)
    {
      Excel ex = GetExcel();
      ex.Open(contextCurrent.Server.MapPath(string.Format("~/ExcelTemplate/{0}.xls", templateName)));
      Worksheet ws = ex.Worksheets[0];

      DataTable dtOut = new DataTable();
      for (int j = 0; j < listFields.Length; ++j)
        dtOut.Columns.Add("Field" + j.ToString(), data.Columns[listFields[j]].DataType);

      foreach (DataRow dr in data.Rows)
      {
        DataRow drData = dtOut.NewRow();
        foreach (DataColumn dc in dtOut.Columns)
        {
          drData[dc.ColumnName] = dr[listFields[dc.Ordinal]];
        }
        dtOut.Rows.Add(drData);
      }

      ws.Cells.ImportDataTable(dtOut, false, startRow, 0);
      startRow += dtOut.Rows.Count + 1;

      if (showResult)
      {
        ex.Save(string.Format("{0}Download.xls", templateName), FileFormatType.Excel2003, SaveType.OpenInExcel, contextCurrent.Response);
        contextCurrent.Response.End();
      }

      return ex;
    }

    /// <summary>
    /// Out data to Excel according to grid
    /// </summary>
    /// <param name="data">Data array</param>
    /// <param name="grid">Grid</param>
    /// <param name="ws">Excel worksheet</param>
    /// <param name="writeHeader">Flag: true - out header, false - no</param>
    /// <param name="startRow">First row number</param>
    public static void GridToExcel(DataTable data, RadGrid grid, Worksheet ws, bool writeHeader, ref int startRow)
    {
      DataTable dtOut = new DataTable();
      DataTable dtHeader = new DataTable();
      List<string> lstGridColumnName = new List<string>();

      DataTable dtOrder = new DataTable();
      dtOrder.Columns.Add("ColumnIndex", typeof(int));
      dtOrder.Columns.Add("OrderedIndex", typeof(int));

      for (int i = 0; i < grid.Columns.Count; ++i)
        dtOrder.LoadDataRow(new object[] { i, grid.Columns[i].OrderIndex }, true);

      DataView dvOrder = new DataView(dtOrder, "", "OrderedIndex", DataViewRowState.CurrentRows);
      for (int j = 0; j < dvOrder.Count; ++j)
      {
        int i = Convert.ToInt32(dvOrder[j]["ColumnIndex"]);

        if ((!grid.Columns[i].Display) || (!grid.Columns[i].Visible))
          continue;

        string dataField = "";

        if (grid.Columns[i] is GridBoundColumn)
          dataField = (grid.Columns[i] as GridBoundColumn).DataField;
        else if (grid.Columns[i] is GridTemplateColumn)
          dataField = (grid.Columns[i] as GridTemplateColumn).DataField;
        else if (grid.Columns[i] is GridHyperLinkColumn)
          dataField = (grid.Columns[i] as GridHyperLinkColumn).DataTextField;

        if (dataField == "")
          continue;

        dtOut.Columns.Add("Field" + i.ToString(), data.Columns[dataField].DataType);
        lstGridColumnName.Add(dataField);
        dtHeader.Columns.Add("Header" + i.ToString(), typeof(string));
      }

      foreach (DataRow dr in data.Rows)
      {
        DataRow drData = dtOut.NewRow();
        foreach (DataColumn dc in dtOut.Columns)
        {
          drData[dc.ColumnName] = dr[lstGridColumnName[dc.Ordinal]];
        }
        dtOut.Rows.Add(drData);
      }

      DataRow drHeader = dtHeader.NewRow();
      for (int i = 0; i < grid.Columns.Count; ++i)
      {
        if ((!grid.Columns[i].Display) || (!grid.Columns[i].Visible))
          continue;

        string dataField = "";

        if (grid.Columns[i] is GridBoundColumn)
          dataField = (grid.Columns[i] as GridBoundColumn).DataField;
        else if (grid.Columns[i] is GridTemplateColumn)
          dataField = (grid.Columns[i] as GridTemplateColumn).DataField;
        else if (grid.Columns[i] is GridHyperLinkColumn)
          dataField = (grid.Columns[i] as GridHyperLinkColumn).DataTextField;

        if (dataField == "")
          continue;

        drHeader["Header" + i.ToString()] = grid.Columns[i].HeaderText;
      }
      dtHeader.Rows.Add(drHeader);

      if (writeHeader)
      {
        ws.Cells.ImportDataTable(dtHeader, false, startRow, 0);
        for (int i = 0; i < dtHeader.Columns.Count; ++i)
          ws.Cells[startRow, i].Style.Font.IsBold = true;
        ++startRow;
      }

      ws.Cells.ImportDataTable(dtOut, false, startRow, 0);
      startRow += dtOut.Rows.Count + 1;
    }

    //Logs errors by sending exception details to a specified administrator
    public static void LogError(Exception ex)
    {
      //get the current date and time
      string dateTime = DateTime.Now.ToLongDateString() + ", at " + DateTime.Now.ToShortTimeString();
      //stores the error message
      string errorMessage = "Exception generated on " + dateTime;
      //obtain the page that generated the error
      System.Web.HttpContext context = System.Web.HttpContext.Current;
      errorMessage += "\n\n Page location: " + context.Request.RawUrl;
      //build the error message
      errorMessage += "\n\n Message: " + ex.Message;
      errorMessage += "\n\n Source: " + ex.Source;
      errorMessage += "\n\n Method: " + ex.TargetSite;
      errorMessage += "\n\n Stack Trace: " + ex.StackTrace;

      string from = ApplicationConfiguration.EmailFrom;
      string to = ApplicationConfiguration.EmailTo;
      string subject = "Real Estate error report";
      string body = errorMessage;
      SendMail(from, to, subject, body);
    }

    //Check for mobile device
    public static bool isMobileBrowser()
    {
      //GETS THE CURRENT USER CONTEXT
      HttpContext context = HttpContext.Current;

      //FIRST TRY BUILT IN ASP.NT CHECK
      if (context.Request.Browser.IsMobileDevice)
      {
        return true;
      }
      //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
      if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
      {
        return true;
      }
      //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
      if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
          context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
      {
        return true;
      }
      //AND FINALLY CHECK THE HTTP_USER_AGENT 
      //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
      if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
      {
        //Create a list of all mobile types
        string[] mobiles =
            new[]
                {
                     "iphone" , "ipad"
                };

        //Loop through each item in the list created above 
        //and check if the header contains that text
        foreach (string s in mobiles)
        {
          if (context.Request.ServerVariables["HTTP_USER_AGENT"].
                                              ToLower().Contains(s.ToLower()))
          {
            return true;
          }
        }
      }

      return false;
    }

    public static GridColumn CreateBoundColumn(string dataField, string headerText)
    {
        return CreateBoundColumn(dataField, headerText, false);
    }

    public static GridColumn CreateBoundColumn(string dataField, string headerText, bool convertEmptyStringToNull)
    {
      GridBoundColumn col = new GridBoundColumn();
      col.DataField = dataField;
      col.HeaderText = headerText;
      col.ConvertEmptyStringToNull = convertEmptyStringToNull;
      col.EditFormColumnIndex = 0;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      return(col);
    }

    public static GridColumn CreateHLColumn(string dataField, string headerText, string dataNavigateUrlFormatString, string[] dataNavigateUrlFields, Unit width)
    {
      GridHyperLinkColumn hlc = new GridHyperLinkColumn()
      {
        HeaderText = headerText,
        DataNavigateUrlFormatString = dataNavigateUrlFormatString,
        DataNavigateUrlFields = dataNavigateUrlFields,
        EditFormColumnIndex = 0,
        DataTextField = dataField,
        SortExpression = dataField
      };
      hlc.HeaderStyle.Width = width;
      return (hlc);
    }

    public static GridColumn GetColumn(GridColumnCollection columns, string name)
    {
      return columns.FindByUniqueNameSafe(name);
    }


    public static int GetColumnIndex(GridColumnCollection columns, string dataField)
    {
      for (int i = 0; i < columns.Count; i++)
      {
        if (columns[i].IsBoundToFieldName(dataField)) return i;
      }
      return 0;
    }

    public static void MoveColumn(GridColumnCollection columns, string name, ref int newIndex)
    {
      GridColumn gc;

      gc = GetColumn(columns, name);
      if (gc != null)
      {
        columns.Remove(gc);
        columns.AddAt(newIndex, gc);

        ++newIndex;
      }
    }*/
  }
}